package com.junzhiit.nengji.api.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.HttpClientUtils;
import com.junzhiit.nengji.api.service.UserConfigService;
import com.junzhiit.nengji.api.web.exception.UserNotFoundException;
import com.junzhiit.nengji.api.web.util.Constants;
import com.junzhiit.nengji.api.web.util.OrderNumberUtils;
import com.junzhiit.nengji.api.web.util.RequestUtil;
import com.junzhiit.nengji.api.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.api.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.api.web.util.wechat.bean.OrderInfo;
import com.junzhiit.nengji.api.web.util.wechat.bean.PayParam;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.api.web.vo.UserConfigVO;
import com.junzhiit.nengji.dao.RechargeConfigureDAO;
import com.junzhiit.nengji.dao.RechargeRecordDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.model.RechargeConfigure;
import com.junzhiit.nengji.model.RechargeRecord;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.PayWay;
import com.junzhiit.nengji.model.enums.RechargeConfigureGiveType;
import com.junzhiit.nengji.model.enums.RechargeRecordStatus;

@Service
public class UserConfigServiceImpl extends BaseServiceImpl implements UserConfigService {

	@Autowired
	private UserConfigDAO userConfigDAO;

	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private RechargeConfigureDAO rechargeConfigureDAO;
	
	@Autowired
	private RechargeRecordDAO rechargeRecordDAO;

	@Value("${images.user.qrcode.path}")
	private String QR_CODE_PATH;
	
	@Value("${images.data.user.qrcode.path}")
	private String dataQrCodePath;
	
	@Value("${upload.data.user.avatarurl}")
	private String userAvatarurlPath;

	@Value("${upload.temp}")
	private String uploadPath;
	
	@Value("${upload.data.temp}")
	private String uploadDataPath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;
	
	private final String WECHAT_BODY_KEY = "乐鸽订单";

	public UserConfig qrcode(String userId, String avatarUrl) {
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		if (userConfig == null) {
			userConfig = new UserConfig();
			userConfig.setUserId(userId);
			UserConfig newUserConfig = userConfigDAO.insert(userConfig);
			userConfig.setId(newUserConfig.getId());
		}
		if (userConfig != null && StringUtils.isBlank(userConfig.getQrCode())) {
			User user = userDAO.query(userId);
			// 保存头像到本地
			try {
				File file = new File(userAvatarurlPath);
				if (!file.exists()) {
					file.mkdirs();
				}
				HttpClientUtils.imageDownloader(user.getAvatarUrl(), userAvatarurlPath + user.getId() + ".png");
			} catch (Exception e) {
				e.printStackTrace();
			}
			String fileName = userId + ".png";
			WeChatUtils.wxQRCode(backetName,user.getCode(), user.getId(), dataQrCodePath, fileName);
			userConfig.setQrCode(fileName);
			userConfigDAO.update(userConfig);
			WeChatUtils.replaceLogo(dataQrCodePath, userAvatarurlPath, uploadDataPath, fileName);
			try {
				AliyunOSSClientUtil.uploadObject2OSS(new FileInputStream(new File(uploadDataPath+fileName)) , fileName, backetName, QR_CODE_PATH);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				logger.error("上传OSS失败!");
			}
		}
		return userConfig;
	}

	@Override
	public ResultVO onlineRecharge(HttpServletRequest request,String userId, Double money,String tradeType) {
		ResultVO result = new ResultVO();
		User user = userDAO.query(userId);
		if (user == null) {
			throw new UserNotFoundException("用户没找到！");
		}
		RechargeConfigure rechargeConfigure = rechargeConfigureDAO.getRechargeMoney(money);
		
		String orderNumber = OrderNumberUtils.getOrderlNumber();
		
		RechargeRecord rechargeRecord = new RechargeRecord();
		rechargeRecord.setUserId(userId);
		rechargeRecord.setOrderNumber(orderNumber);
		rechargeRecord.setRechargeMoney(money);
		
		rechargeRecord.setPayWay(PayWay.WECHAT.toIntValue());
		//赠送方式
		if(rechargeConfigure!=null){
			rechargeRecord.setGiveType(rechargeConfigure.getGiveType());
		}else{
			rechargeRecord.setGiveType(RechargeConfigureGiveType.MONEY.toIntType());
		}
		//赠送金额
		if(rechargeConfigure!=null && (money<=rechargeConfigure.getRechargeMoney())){
			rechargeRecord.setGiveValue(rechargeConfigure.getGiveValue());
		}else{
			rechargeRecord.setGiveValue(0.0);
		}
		rechargeRecord.setStatus(RechargeRecordStatus.UNPAID.toIntValue());
		RechargeRecord param = rechargeRecordDAO.insert(rechargeRecord);
		// 微信支付
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAttach(Constants.WECHAT_ATTACH_FOR_RECHARGE);
		orderInfo.setOutTradeNo(orderNumber);
		orderInfo.setBody(WECHAT_BODY_KEY + "-" + orderNumber);
		orderInfo.setTotalFee(Math.round(money * 100));
		orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
		orderInfo.setOpenId(user.getOpenId());
		orderInfo.setTradeType(tradeType);
		PayParam payParam = WeChatUtils.getPayParam(orderInfo);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rechargeRecord", param.getOrderNumber());
		map.put("rechargeRecordId", param.getId());
		map.put("patParam", payParam);
		result.setData(map);
		return result;
	}

	@Override
	public UserConfigVO getUserConfigById(String userId) {
		UserConfigVO userConfigVO = new UserConfigVO();
		UserConfig userConfig = userConfigDAO.getUserConfig(userId);
		BeanUtils.copyProperties(userConfig,userConfigVO);
		return userConfigVO;
	}

	@Override
	public ResultVO updateQrcode() {
		List<User> list = userDAO.findUserList();
		for(User user :list){
			String name = user.getId()+".png";
			try {
				HttpClientUtils.imageDownloader(user.getAvatarUrl(), userAvatarurlPath + user.getId() + ".png");
				WeChatUtils.wxQRCode(backetName, user.getCode(), user.getId(), dataQrCodePath, name);
				WeChatUtils.replaceLogo(dataQrCodePath, userAvatarurlPath, uploadDataPath, name);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			try {
				AliyunOSSClientUtil.uploadObject2OSS(new FileInputStream(new File(uploadDataPath+name)) , name, backetName, QR_CODE_PATH);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			System.out.println(name);
		}
		return null;
	}

	/*
	 * public ResultVO getAvatarur(){ User user = new User(); List<User> list =
	 * userDAO.findByUser(user); try { for(User params : list){ //UserConfig
	 * userConfig = userConfigDAO.getUserConfig(params.getId());
	 * if(StringUtils.isNoneBlank(params.getAvatarUrl())){
	 * HttpClientUtils.imageDownloader(params.getAvatarUrl(),userAvatarurlPath+
	 * params.getId()+".png"); String fileName = params.getId() + ".png";
	 * System.err.println("------------------>"+fileName);
	 * //WeChatUtils.wxQRCode(user.getCode(), user.getId(),
	 * QR_CODE_PATH,fileName); //userConfig.setQrCode(fileName);
	 * //userConfigDAO.update(userConfig);
	 * WeChatUtils.replaceLogo(QR_CODE_PATH,userAvatarurlPath,uploadPath,
	 * fileName); } } } catch (Exception e) { e.printStackTrace(); } return
	 * null; }
	 */
}
